package com.easy.admin.system.controller;

import com.easy.admin.system.annon.FormToken;
import com.easy.admin.system.comnon.UUIDUtil;
import com.easy.admin.system.dao.elasticsearch.ElasticSearchDao;
import com.easy.admin.system.model.Persion;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author wangbo
 */
@RestController
@RequestMapping("/es")
public class ElasticSearchTestController {
    @Autowired
    private ElasticSearchDao elasticSearchDao;

    @RequestMapping("/add")
    public Object add(String name, Integer sex, String phone) {
        Persion p = new Persion();
        p.setId(UUIDUtil.get32UUIDIsLowerCase());
        p.setUserName(name);
        p.setSex(sex);
        p.setAddress("Test address");
        p.setPhoneNum(phone);
        //QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(name);
        //SearchQuery searchQuery ;
        elasticSearchDao.save(p);
        return true;
    }

    @FormToken(name="test",saveToken = false)
    @RequestMapping("/getAll")
    public Object getAll() {
        Iterable<Persion> persions = elasticSearchDao.findAll();
        Iterator<Persion> it = persions.iterator();
        List<Persion> lists = new ArrayList<>();
        while (it.hasNext()) {
            Persion p = it.next();
            lists.add(p);
        }
        return lists;
    }

    @RequestMapping("/getPersionById")
    public Object getPersionById(String id) {
        return elasticSearchDao.queryPersionById(id);
    }

    @RequestMapping("/selectByKewWords")
    public Object selectByKewWords(String keywords) {
        QueryBuilder qb = QueryBuilders.matchPhraseQuery("userName", keywords);
        Iterable<Persion> persions = elasticSearchDao.search(qb);
        Iterator<Persion> it = persions.iterator();
        List<Persion> lists = new ArrayList<>();
        while (it.hasNext()) {
            Persion p = it.next();
            lists.add(p);
        }
        return lists;
    }
}
